const BaseService = require('./base_service.js');
const DeviceDurationPricingModel = require('../model/device_duration_pricing_model.js');

class DurationPricingService extends BaseService {

  /**
   * 添加时长档位
   */
  async addDurationPricing(input) {
    const db = uniCloud.database();
    const collection = db.collection(DeviceDurationPricingModel.CL);

    // 检查设备是否存在
    const DeviceModel = require('../model/device_model.js');
    const deviceCollection = db.collection(DeviceModel.CL);
    const device = await deviceCollection.doc(input.deviceId).get();
    if (!device.data.length) {
      throw new Error('设备不存在');
    }

    // 检查时长档位是否重复
    const existingPricing = await collection.where({
      deviceId: input.deviceId,
      duration: input.duration
    }).get();

    if (existingPricing.data.length > 0) {
      throw new Error('该时长档位已存在');
    }

    // 计算最终价格
    const finalPrice = Math.round(input.price * (1 - (input.discount || 0)));

    // 创建档位数据
    const pricingData = {
      deviceId: input.deviceId,
      duration: input.duration,
      price: input.price,
      discount: input.discount || 0,
      finalPrice: finalPrice,
      description: input.description || '',
      status: 1, // 默认启用
      sortOrder: 0,
      createTime: Date.now(),
      updateTime: Date.now()
    };

    const result = await collection.add(pricingData);
    
    return {
      pricingId: result.id,
      message: '时长档位添加成功'
    };
  }

  /**
   * 更新时长档位
   */
  async updateDurationPricing(pricingId, input) {
    const db = uniCloud.database();
    const collection = db.collection(DeviceDurationPricingModel.CL);

    // 检查档位是否存在
    const pricing = await collection.doc(pricingId).get();
    if (!pricing.data.length) {
      throw new Error('档位不存在');
    }

    // 更新档位数据
    const updateData = {
      ...input,
      updateTime: Date.now()
    };

    // 如果更新了价格或折扣，重新计算最终价格
    if (input.price !== undefined || input.discount !== undefined) {
      const currentData = pricing.data[0];
      const price = input.price !== undefined ? input.price : currentData.price;
      const discount = input.discount !== undefined ? input.discount : currentData.discount;
      updateData.finalPrice = Math.round(price * (1 - discount));
    }

    await collection.doc(pricingId).update(updateData);

    return { message: '档位更新成功' };
  }

  /**
   * 删除时长档位
   */
  async deleteDurationPricing(pricingId) {
    const db = uniCloud.database();
    const collection = db.collection(DeviceDurationPricingModel.CL);

    // 检查档位是否存在
    const pricing = await collection.doc(pricingId).get();
    if (!pricing.data.length) {
      throw new Error('档位不存在');
    }

    // 软删除
    await collection.doc(pricingId).update({
      status: 0,
      updateTime: Date.now()
    });

    return { message: '档位删除成功' };
  }

  /**
   * 获取设备档位列表
   */
  async getDevicePricingList(deviceId) {
    const db = uniCloud.database();
    const collection = db.collection(DeviceDurationPricingModel.CL);

    // 查询设备的所有档位
    const result = await collection
      .where({
        deviceId: deviceId,
        status: 1 // 只查询启用的档位
      })
      .orderBy('duration', 'asc')
      .get();

    return result.data;
  }
}

module.exports = DurationPricingService;
